from datetime import datetime
import os
import json
from utils.file_handler import FileHandler

class Student:
    def __init__(self, name, student_id):
        self.name = name
        self.student_id = student_id
        self.file_handler = FileHandler()
    
    def take_exam(self, exam_id):
        """答题"""
        try:
            # 使用file_handler加载试卷
            exam = self.file_handler.load_exam(exam_id)
            
            answers = []
            print(f"\n开始答题，共{len(exam['questions'])}道题：")
            
            for question in exam['questions']:
                print(f"\n{question}")
                answer = input("你的答案：")
                answers.append(answer)
            
            # 使用学生ID_试卷ID作为提交ID
            submission_id = f"{self.student_id}_{exam_id}"
            
            submission = {
                'submission_id': submission_id,
                'exam_id': exam_id,
                'student_id': self.student_id,
                'student_name': self.name,
                'answers': answers,
                'submit_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'graded': False
            }
            
            # 使用file_handler保存答卷
            self.file_handler.save_submission(submission)
            
            return submission_id
            
        except FileNotFoundError as e:
            print(f"\n错误：找不到试卷 {exam_id}")
            raise
        except Exception as e:
            print(f"\n错误：{str(e)}")
            raise
    
    def view_wrong_questions(self, submission_id):
        """查看错题分析"""
        try:
            # 使用file_handler加载答卷
            submission = self.file_handler.load_submission(submission_id)
            
            if not submission.get('graded', False):
                print("\n该答卷尚未批改！")
                return None
            
            wrong_questions = submission.get('wrong_questions', [])
            analysis_data = {
                'total_questions': len(submission['answers']),
                'score': submission['score'],
                'wrong_questions': wrong_questions
            }
            
            # 生成HTML报告
            try:
                html_file = self.file_handler.generate_wrong_questions_html(
                    self.student_id,
                    submission['exam_id'],
                    analysis_data
                )
                print("\n" + "="*50)
                print(f"错题分析报告已生成！")
                print(f"文件位置：{html_file}")
                print("正在尝试自动打开报告...")
                print("="*50)
                
                # 打开HTML文件
                os.system(f'start {html_file}')
                
                print("\n如果报告没有自动打开，请手动打开上述文件位置的HTML文件")
                
            except Exception as e:
                print(f"\n生成报告失败：{str(e)}")
            
            return analysis_data
            
        except FileNotFoundError:
            print(f"\n错误：找不到答卷 {submission_id}")
            raise
        except Exception as e:
            print(f"\n错误：{str(e)}")
            raise